package com.lushuai.jiubeidanci.fragment;

import android.content.Intent;
import android.graphics.RenderEffect;
import android.graphics.Shader;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.VideoView;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.lushuai.jiubeidanci.R;
import com.lushuai.jiubeidanci.VideoPlayerActivity;
import com.lushuai.jiubeidanci.adapter.BannerAdapter;
import com.lushuai.jiubeidanci.activity.WordLearnActivity;

public class HomeFragment extends Fragment {
    private VideoView videoView1;
    private ImageView videoThumbnail1;
    private ImageView playButton1;
    private VideoView videoView2;
    private ImageView videoThumbnail2;
    private ImageView playButton2;
    private ViewPager2 bannerViewPager;
    private LinearLayout indicatorContainer;
    private int[] bannerImages = {R.drawable.banner1, R.drawable.banner2, R.drawable.banner3};
    private Handler handler;
    private Runnable bannerRunnable;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 初始化轮播图
        setupBanner(view);
        // 初始化视图
        videoView1 = view.findViewById(R.id.video_view_1);
        videoThumbnail1 = view.findViewById(R.id.video_thumbnail_1);
        playButton1 = view.findViewById(R.id.play_button_1);
        videoView2 = view.findViewById(R.id.video_view_2);
        videoThumbnail2 = view.findViewById(R.id.video_thumbnail_2);
        playButton2 = view.findViewById(R.id.play_button_2);

        // 设置视频1的点击事件
        View.OnClickListener playClickListener1 = v -> {
            Intent intent = new Intent(requireActivity(), VideoPlayerActivity.class);
            intent.putExtra("video_res_id",R.raw.video1);
            startActivity(intent);
        };

        videoThumbnail1.setOnClickListener(playClickListener1);
        playButton1.setOnClickListener(playClickListener1);

        // 设置视频2的点击事件
        View.OnClickListener playClickListener2 = v -> {
            Intent intent = new Intent(requireActivity(), VideoPlayerActivity.class);
            intent.putExtra("video_res_id", R.raw.video2);
            startActivity(intent);
        };

        videoThumbnail2.setOnClickListener(playClickListener2);
        playButton2.setOnClickListener(playClickListener2);

        // 在初始化视图后添加以下代码
        setupBlurEffect(view);
        
        View learnCard = view.findViewById(R.id.learn_card);
        learnCard.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WordLearnActivity.class);
            startActivity(intent);
        });
        
        return view;
    }
    
    private void setupBanner(View view) {
        bannerViewPager = view.findViewById(R.id.banner_viewpager);
        indicatorContainer = view.findViewById(R.id.indicator_container);
        
        // 设置轮播图适配器
        BannerAdapter adapter = new BannerAdapter(bannerImages);
        bannerViewPager.setAdapter(adapter);
        
        // 设置初始位置
        int startPosition = Integer.MAX_VALUE / 2;
        startPosition = startPosition - (startPosition % bannerImages.length);
        bannerViewPager.setCurrentItem(startPosition, false);
        
        // 创建指示器
        setupIndicators(bannerImages.length);
        
        // 设置页面切换监听
        bannerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                updateIndicators(position % bannerImages.length);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    // 当滚动停止时，继续自动轮播
                    startAutoScroll();
                } else if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    // 当用户开始拖动时，停止自动轮播
                    stopAutoScroll();
                }
            }
        });
        
        // 开始自动轮播
        startAutoScroll();
    }
    
    private void setupIndicators(int count) {
        ImageView[] indicators = new ImageView[count];
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(8, 0, 8, 0);
        
        for (int i = 0; i < count; i++) {
            indicators[i] = new ImageView(requireContext());
            indicators[i].setImageResource(i == 0 ? 
                    R.drawable.indicator_selected : R.drawable.indicator_unselected);
            indicators[i].setLayoutParams(params);
            indicatorContainer.addView(indicators[i]);
        }
    }
    
    private void updateIndicators(int position) {
        int childCount = indicatorContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ImageView imageView = (ImageView) indicatorContainer.getChildAt(i);
            imageView.setImageResource(i == position ? 
                    R.drawable.indicator_selected : R.drawable.indicator_unselected);
        }
    }
    
    private void startAutoScroll() {
        if (handler == null) {
            handler = new Handler();
        }
        stopAutoScroll(); // 先停止之前的轮播
        
        bannerRunnable = new Runnable() {
            @Override
            public void run() {
                if (bannerViewPager != null) {
                    bannerViewPager.setCurrentItem(bannerViewPager.getCurrentItem() + 1);
                    handler.postDelayed(this, 3000);
                }
            }
        };
        handler.postDelayed(bannerRunnable, 3000);
    }
    
    private void stopAutoScroll() {
        if (handler != null && bannerRunnable != null) {
            handler.removeCallbacks(bannerRunnable);
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopAutoScroll();
        handler = null;
        if (videoView1 != null) {
            videoView1.stopPlayback();
        }
        if (videoView2 != null) {
            videoView2.stopPlayback();
        }
    }

    // 添加这个新方法
    private void setupBlurEffect(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // 只对背景View应用模糊效果
            View learnBlurBackground = view.findViewById(R.id.learn_blur_background);
            View reviewBlurBackground = view.findViewById(R.id.review_blur_background);

            RenderEffect blurEffect = RenderEffect.createBlurEffect(
                    10f,  // 模糊半径
                    10f,  // 模糊半径
                    Shader.TileMode.CLAMP
            );

            // 只对背景应用模糊效果
            learnBlurBackground.setRenderEffect(blurEffect);
            reviewBlurBackground.setRenderEffect(blurEffect);
        }
    }
}